package com.ruyuan.twelve.juc._08.guarded.suspension;

import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

public class GuardedQueue {
    private final Queue<Integer> sourceList;

    public GuardedQueue() {
        this.sourceList = new LinkedBlockingQueue<>();
    }

    //先获取锁
    public synchronized Integer get() {
        //检测是否有门票
        while (sourceList.isEmpty()) {
            try {
                wait();    // <--- 如果队列为null，即没有门票，释放锁并且吊起等待
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return sourceList.peek();
    }

    //放入门票并且通知所有线程进行抢夺
    public synchronized void put(Integer e) {
        sourceList.add(e);
        notifyAll();  //<--- 通知，继续执行    }
    }
}